<template>
  <div class="message-item" :class="{ 'self': isSelf }">
    <p class="time">
      <span>{{ msgAt }}</span>
    </p>
    <div class="main">
      <img
          :src="avatar"
          class="avatar"
      />
      <div class="pic" v-if="isImgType" @click="preview(msg)"><img :src="msg" alt=""></div>
      <div class="text" v-else v-html="msg"></div>
    </div>
  </div>
</template>

<script>
import {computed} from 'vue'
import {dateFormat} from "../../utils/helper"
import config from "../../config"

export default {
  name: "MessageItem",
  props: {
    message: {
      type: Object,
      required: true,
    }
  },
  emits: ["picturePreview"],
  setup(props, context) {
    const preview = (pic) => {
      console.log(pic)
      context.emit('picturePreview', pic)
    }

    const isSelf = props.message.from == 1

    const avatar = isSelf ? '/public/guest.png' : '/public/kf.png'

    const time = props.message.created_at || +new Date
    const msgAt = dateFormat(time, 'yyyy-MM-dd HH:mm:ss')

    const isImgType = props.message.type == 3

    const msg = isImgType
        ? config.apiUrl + props.message.content
        : props.message.content.replace(/\[em_([0-9]*)\]/g, '<img src="/public/face/$1.gif"/>')

    return {
      msg,
      isSelf,
      avatar,
      msgAt,
      isImgType,
      preview,
    }
  }
}
</script>

<style scoped>
.message-item {
  margin-bottom: 15px;
}

.time {
  margin: 7px 0;
  text-align: center;
}

.time span {
  display: inline-block;
  font-size: 12px;
  color: #aaa;
}

.avatar {
  float: left;
  margin: 0 10px 0 0;
  height: 35px;
  width: 35px;
}

.text {
  display: inline-block;
  position: relative;
  padding: 7px 10px;
  max-width: 50%;
  font-size: 14px;
  text-align: left;
  word-break: break-all;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 3px rgba(18, 18, 18, 0.1);
}

.text:before {
  content: " ";
  position: absolute;
  top: 9px;
  right: 100%;
  border: 6px solid transparent;
  border-right-color: #fff;
}

.main {
  text-align: left;
}

.self .main {
  text-align: right;
}

.self .avatar {
  float: right;
  margin: 0 0 0 10px;
}

.self .text {
  background-color: #cce6ff;
  box-shadow: none;
}

.self .text:before {
  right: inherit;
  left: 100%;
  border-right-color: transparent;
  border-left-color: #cce6ff;
}

.pic {
  border-radius: 7px;
  height: auto;
  overflow: hidden;
  padding: 0;
  max-width: 250px;
  box-sizing: border-box;
  display: inline-block;
}

.pic img {
  width: 100%;
  padding: 0;
  margin: 0;
  vertical-align: middle;
  height: auto;
}
@media screen and (max-width: 720px) {
  .pic {
    max-width: 45%;
  }
}
</style>